package com.cory.module.job.core;

import java.util.List;
import lombok.SneakyThrows;
import com.cory.boot.component.cache.RedisUtils;
import com.cory.boot.utils.SpringUtils;
import com.cory.boot.utils.TaskPoolUtils;
import com.cory.module.job.domain.entity.JobAsync;
import com.cory.module.job.domain.entity.JobExcelExport;
import com.cory.module.job.domain.entity.JobExcelImport;
import com.cory.module.job.service.JobAsyncService;
import com.cory.module.job.service.JobExcelExportService;
import com.cory.module.job.service.JobExcelImportService;
import com.google.common.collect.Lists;

/**
 * @author xiongcong
 * @date 2023-05-09
 */
public class JobRunner {

    @SneakyThrows
    public static void runAsyncJob(int size) {
        RedisUtils.lock("AsyncJob", 1, () -> {
            List<JobAsync> jobs = SpringUtils.getBean(JobAsyncService.class).runList(size);
            if (jobs.size() == 0) {
                return true;
            }

            List<Runnable> tasks = Lists.newArrayList();
            jobs.forEach(job -> {
                tasks.add(() -> JobFactory.getAsyncJobHandle(job.getType()).run(job));
            });
            TaskPoolUtils.runFuture(tasks);
            return true;
        });
    }

    @SneakyThrows
    public static void runExcelExportJob(int size) {
        RedisUtils.lock("ExcelExportJob", 1, () -> {
            List<JobExcelExport> jobs = SpringUtils.getBean(JobExcelExportService.class).runList(size);
            if (jobs.size() == 0) {
                return true;
            }

            List<Runnable> tasks = Lists.newArrayList();
            jobs.forEach(job -> {
                tasks.add(() -> JobFactory.getExcelExportJobHandle(job.getType()).run(job));
            });
            TaskPoolUtils.runFuture(tasks);
            return true;
        });
    }

    @SneakyThrows
    public static void runExcelImportJob(int size) {
        RedisUtils.lock("ExcelImportJob", 1, () -> {
            List<JobExcelImport> jobs = SpringUtils.getBean(JobExcelImportService.class).runList(size);
            if (jobs.size() == 0) {
                return true;
            }

            List<Runnable> tasks = Lists.newArrayList();
            jobs.forEach(job -> {
                tasks.add(() -> JobFactory.getExcelImportJobHandle(job.getType()).run(job));
            });
            TaskPoolUtils.runFuture(tasks);
            return true;
        });
    }
}
